package vip.hello520.config;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import vip.hello520.enums.PropFileEnum;
import vip.hello520.util.ZkUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 把磁盘目录的db.properties文件的数据加载进zk
 *
 * @author 大宝杰
 */
public class ZkPropConfigUp {
    private static final Logger logger = LoggerFactory.getLogger(ZkPropConfigUp.class);

    /**
     * zk服务器地址
     */
    private String zkUrl;
    /**
     * zk中,存储配置文件的节点的父节点
     */
    private String zkNameSpace;

    public static void main(String[] args) {
        new ZkPropConfigUp().upProConfigToZk();
    }

    /**
     * 为了增强通用性,zkUrl做成可配置的
     */
    private void initUrl() {
        Properties prop = new Properties();
        ClassPathResource resource = new ClassPathResource("zk.properties");
        try (InputStream inputStream = resource.getInputStream()) {
            prop.load(inputStream);
            this.zkUrl = prop.getProperty("zkUrl");
            this.zkNameSpace = prop.getProperty("zkNameSpace");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从一个物理路径将.properties文件的配置信息加载进ZK的一个节点
     */
    private void upProConfigToZk() {
        initUrl();
        try (CuratorFramework zkClient = ZkUtils.getZkClient(zkUrl, zkNameSpace)) {
            PropFileEnum[] values = PropFileEnum.values();
            for (PropFileEnum fileEnum : values) {
                String propFilePath = "C:/Users/Hello/Desktop/zk/" + fileEnum.getK();
                String loadToProp = Objects.requireNonNull(propFileLoadToProp(propFilePath)).toString();
                String zNodeName = propFilePath.substring(propFilePath.lastIndexOf("/"), propFilePath.lastIndexOf("."));
                if (!ZkUtils.exists(zkClient, zNodeName)) {
                    zkClient.create()
                            .creatingParentContainersIfNeeded()
                            .withMode(CreateMode.PERSISTENT)
                            .forPath(zNodeName, loadToProp.getBytes());
                } else {
                    zkClient.setData().forPath(zNodeName, loadToProp.getBytes());
                }
                logger.info("properties文件的数据已经加载进zk了,节点名:{}参数:{}", zNodeName, loadToProp);
            }
        } catch (Exception e) {
            logger.error("出错了:{}", e);
        }
    }

    /**
     * 从物理路径将.properties文件的资源加载进一个 Properties对象里
     *
     * @param propFilePath
     * @return
     */
    private Properties propFileLoadToProp(String propFilePath) {
        Properties properties = new Properties();
        File file = new File(propFilePath);
        if (!file.exists()) {
            logger.info("文件:{}", propFilePath + " 不存在");
            return null;
        }
        try (InputStream is = new FileInputStream(file)) {
            Properties prop = new Properties();
            prop.load(is);
            Set<Object> set = prop.keySet();
            if (!set.isEmpty()) {
                for (Object key : set) {
                    String k = (String) key;
                    String v = prop.getProperty(k);
                    properties.put(k, ZkUtils.encode(v));
                }
            }
        } catch (IOException e) {
            logger.error("配置参数加载失败,请检查配置文件是否正确");
        }
        return properties;
    }
}
